import React, { useEffect, useRef, useState } from 'react';
import {
  Button,
  Card,
  Checkbox,
  Form,
  Input,
  Select,
  Space,
  Modal,
  message,
  InputNumber,
  Col,
} from 'antd';
import {
  getBuildingsList,
  getBuildingsView,
  getRoomTypeList,
  getRoomTypeView,
} from '../../BuildingType/request';
import { GenerateRoomList } from '../utils';
import { postRoomsBatchAdd } from '../request';
import { ActionType, ProTable } from '@ant-design/pro-components';
import { GithubIssueItem } from '..';
import { useIntl } from '@umijs/max';
import { Row } from 'antd/lib';
const { Option } = Select;
const { confirm } = Modal;
interface Prpos {
  setIsModalOpen: (event: boolean) => void;
} 

const GenerateRooms: React.FC<Prpos> = ({ setIsModalOpen }) => {
  const [includeChild, setIncludeChild] = useState(false);
  const [list, setList] = useState([]);

  const intl = useIntl()

  // 创建表单实例
  const [form] = Form.useForm();
  // 表格操作源
  const actionRef = useRef<ActionType>();
  // 切换子房间
  const handleCheckboxChange = (e: any) => {
    setIncludeChild(e.target.checked);
  };

  // 锁类型
  const suolist = [
    { label: intl.formatMessage({id:'RoomSettings.Single'}), value: 1 },
    { label: '2.4G', value: 2 },
    { label: 'BLE', value: 3 },
  ];

  // 房间类型
  const [roomTypeList, setRoomTypeList] = useState([]);
  const getRoomType = async () => {
    const res = await getRoomTypeList();
    const data = res.data.list || [];
    const list = data.map((v: any, index: number) => {
      return { label: v.name, value: v.id, key: index };
    });
    setRoomTypeList(list || []);
  };

  // 获取可选择楼栋
  const [buildingList, setBuildingList] = useState([]);
  const getBuilding = async () => {
    const res = await getBuildingsList({});
    const data = res.data.list || [];
    const list = data.map((v: any) => {
      return {
        label: `${v.bno}${intl.formatMessage({id:'FixLock.building'})}`,
        value: v.id,
      };
    });
    setBuildingList(list ? list : []);
  };
  useEffect(() => {
    getBuilding();
    getRoomType();
  }, []);

  // 可选择的楼层
  const [floorList, setFloorList] = useState([]);

  // 楼栋改变时
  const changeBuilding = async (value: any) => {
    form.setFieldsValue({
      selectFloor: [],
    });
    const res = await getBuildingsView(value);
    const floor = res.data.floor || [];
    const list = floor.split(',').map((v: string) => {
      return {
        label: v,
        value: v.slice(0, -1),
      };
    });
    setFloorList(list);
  };

  // 生成的数据
  const generate = () => {
    form.validateFields().then(async (formData) => {
      const {
        data: { bno },
      } = await getBuildingsView(Number(formData.buildingId));

      const {
        data: { name }, 
      } = await getRoomTypeView(Number(formData.room_type_id));


      // console.log(formData.excludeNumber.split(","))
      

      console.log(formData);

      const list = GenerateRoomList({ ...formData,excludeNumber:formData.excludeNumber?formData.excludeNumber.split(","):"", buildingName: bno, roomTypeName: name });
      setList(list ? list : []);
    });
  };  

  // 入库
  const bePut = async () => {
    const res: any = await postRoomsBatchAdd(list);
    if (res.code !== 0) return message.error(res.msg);
    message.success(intl.formatMessage({id:"RoomSettings.added to the inventory!"}));
    setIsModalOpen(false);
    return;
  };

  // 删除房间
  const deleteRoom = (record: any) => {
    const { isSuite, roomId, id, mainRoomId } = record;
    // 不是主房间的只需要过滤掉这个房间就行
    if (!isSuite) {
      const arr = list.filter((v: any) => v.id !== id);
      // 如果删除的是主房间下的附属房间--还要将主房间的子房间数-1
      if (mainRoomId) {
        arr.forEach((v: any) => {
          if (v.roomId === mainRoomId) {
            v.subRoomCount -= 1;
            if (v.subRoomCount === 0) {
              v.isSuite = 0;
            }
          }
        });
      }
      setList(arr);
    } else {
      const arr1 = list.filter((v: any) => v.id !== id);
      const arr2 = arr1.filter((v: any) => v.mainRoomId !== roomId);
      setList(arr2);
    }
  };

  // 修改信息
  const editRow = async (data: any) => {
    if (!data) return;
    console.log(data);
    const {
      data: { name },
    } = await getRoomTypeView(Number(data.roomTypeName));
    const list1 = list;
    list1.forEach((v: any) => {
      if (v.id === data.id) {
        v.roomName = data.roomName;
        if (!name) return;
        v.roomTypeId = data.roomTypeName;
        v.roomTypeName = name;
      }
    });

    setList(list1 ? list1 : []);
    actionRef.current?.reload();
  };

  // 单击一行触发的事件---点击一行时触发修改这一行的操作
  const handleRowClick = (record: GithubIssueItem) => {
    console.log(record);
    
    actionRef.current?.startEditable(record.id);
  };

  const columns: any = [
    {
      title: intl.formatMessage({id:'FixLock.serial'}),
      valueType: 'index',
      width: 68,
      editable: false,
    },
    {
      title: intl.formatMessage({id:'FixLock.Building'}),
      dataIndex: 'buildingName',
      editable: false,
      render: (_text: any, record: any) => {
        return `${record.buildingName}${intl.formatMessage({id:'FixLock.building'})}`;
      },
    },
    {
      title: intl.formatMessage({id:'FixLock.Floor'}),
      dataIndex: 'floor',
      editable: false,
    },
    {
      title:intl.formatMessage({id:'FixLock.Room Type'}),
      dataIndex: 'roomTypeName',
      valueType: 'select',
      renderFormItem: () => {
        return <Select style={{ width: '100%' }} options={roomTypeList} placeholder={intl.formatMessage({id:"RoomSettings.Please select the room type"})} />;
      },
    },
    {
      title: intl.formatMessage({id:"RoomSettings.room"})+' ID',
      dataIndex: 'roomId',
      editable: false,
    },
    {
      title: intl.formatMessage({id:'FixLock.Room number'}),
      dataIndex: 'roomNo',
      editable: false,
    },
    {
      title: intl.formatMessage({id:'RoomSettings.Room name'}),
      dataIndex: 'roomName',
    },

    {
      title: intl.formatMessage({id:"RoomSettings.Is suite"}),
      dataIndex: 'isSuite',
      editable: false,
      render(tags: any) {
        let wenben = Number(tags);
        if (wenben === 0) {
          return intl.formatMessage({id:"RoomSettings.No"});
        } else if (wenben === 1) {
          return intl.formatMessage({id:"RoomSettings.Yes"});
        }
        return intl.formatMessage({id:"RoomSettings.Unknown"});
      },
    },
    {
      title: intl.formatMessage({id:'RoomSettings.Main room'}) +' ID',
      dataIndex: 'mainRoomId',
      editable: false,
    },

    {
      title: intl.formatMessage({id:"RoomSettings.Number of bedrooms"}),
      dataIndex: 'subRoomCount',
      editable: false,
    },
    {
      title: intl.formatMessage({id:"RoomSettings.Lock type"}),
      dataIndex: 'lockType',
      editable: false,
      render(tags: any) {
        if (tags === 1) {
          return intl.formatMessage({id:"RoomSettings.Single"});
        } else if (tags === 2) {
          return '2.4G';
        } else if (tags === 3) {
          return 'BLE';
        }
        return intl.formatMessage({id:"RoomSettings.Unknown"});
      },
    },
    {
      title: intl.formatMessage({id:"FixLock.Action"}),
      align: 'center',
      valueType: 'option',
      key: 'option',
      render: (_: any, record: any) => (
        <Space size="middle">
          <a
            onClick={() => {
              confirm({
                title: intl.formatMessage({id:"RoomSettings.Do you want to delete it"}),
                content:intl.formatMessage({id:"RoomSettings.Deleting attached subrooms"}),
                okText: 'ok',
                okType: 'danger',
                cancelText: 'Cancel',
                onOk: () => {
                  deleteRoom(record);
                },
                onCancel: () => {},
              });
            }}
          >
            {/* 删除 */}
            {intl.formatMessage({id:"FixLock.delete"})}
          </a>
        </Space>
      ),
    },
  ];

  // 生成表格数据之后，将每行数据都打开修改模式----影响性能
  // useEffect(() => {
  //   list.forEach((v: any) => {
  //     actionRef?.current?.startEditable(v.id);
  //   });
  // }, [list]);

  return (
    <>
      <Card  style={{ width: '100%' }}>
      <Form
      form={form}
      layout="horizontal"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 'none' }}
    >
      {/* 第一行 */}
      <Row gutter={24}>
        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={`${intl.formatMessage({ id: "RoomSettings.Select building" })}:`}
            name="buildingId"
            rules={[{ required: true }]}
          >
            <Select
              onChange={changeBuilding}
              placeholder={intl.formatMessage({ id: "RoomSettings.Please select a building" })}
              style={{ width: '100%' }}
            >
              {buildingList.map((d) => (
                <Option key={d.value} value={d.value}>
                  {d.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Col>

        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={`${intl.formatMessage({ id: "RoomSettings.Select Floor" })}:`}
            name="selectFloor"
            rules={[{ required: true }]}
          >
            <Select
              mode="multiple"
              placeholder={intl.formatMessage({ id: "RoomSettings.Select Floor" })}
              style={{ width: '100%' }}
              options={floorList}
            />
          </Form.Item>
        </Col>

        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={`${intl.formatMessage({ id: "RoomSettings.Select Room type" })}:`}
            name="room_type_id"
            rules={[{ required: true }]}
          >
            <Select
              placeholder={intl.formatMessage({ id: "RoomSettings.Please select the room type" })}
              style={{ width: '100%' }}
            >
              {roomTypeList.map((v) => (
                <Option key={v.value} value={v.value}>
                  {v.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Col>

        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={`${intl.formatMessage({ id: "RoomSettings.Lock type" })}:`}
            name="lockType"
            initialValue={3}
            rules={[{ required: true }]}
          >
            <Select
              placeholder={intl.formatMessage({ id: "RoomSettings.Please select lock type" })}
              style={{ width: '100%' }}
            >
              {suolist.map((v) => (
                <Option key={v.value} value={v.value}>
                  {v.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Col>
      </Row>

      {/* 第二行 */}
      <Row gutter={24}>
        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={`${intl.formatMessage({ id: "RoomSettings.Start number" })}:`}
            name="startNumber"
            rules={[{ required: true }]}
          >
            <InputNumber
              min={1}
              max={255}
              style={{ width: '100%' }}
              placeholder={intl.formatMessage({ id: "RoomSettings.Please enter Starting number" })}
            />
          </Form.Item>
        </Col>

        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={`${intl.formatMessage({ id: "RoomSettings.End number" })}:`}
            name="endNumber"
            dependencies={['startNumber']}
            rules={[
              { required: true },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (getFieldValue('startNumber') <= value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error(intl.formatMessage({ id: "RoomSettings.starting End number" })));
                },
              }),
            ]}
          >
            <InputNumber
              min={1}
              max={255}
              style={{ width: '100%' }}
              placeholder={intl.formatMessage({ id: "RoomSettings.Please enter End number" })}
            />
          </Form.Item>
        </Col>

        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={intl.formatMessage({ id: "RoomSettings.Prefix" })}
            name="prefix"
          >
            <Input
              placeholder={intl.formatMessage({ id: "RoomSettings.Please enter the prefix" })}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Col>

        <Col xs={24} md={12} lg={6}>
          <Form.Item
            label={intl.formatMessage({ id: "RoomSettings.Exclude the last digit" })}
            name="excludeNumber"
          >
            <Input
              placeholder={intl.formatMessage({ id: "RoomSettings.Excluding numbers, division." })}
              style={{ width: '100%' }}
            />
          </Form.Item>
        </Col>
      </Row>

      {/* 套间设置行 */}
      <Row gutter={24}>
        <Col span={24}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Form.Item
              name="isSuite"
              valuePropName="checked"
              style={{ width: '200px',marginLeft:60 }}
            >
              <Checkbox onChange={handleCheckboxChange}>
                {intl.formatMessage({ id: "RoomSettings.Is suite" })}
              </Checkbox>
            </Form.Item>
            
            {includeChild && (
              <Form.Item
                label={intl.formatMessage({ id: "RoomSettings.Number of Suites" })}
                name="subRoomCount"
              
              >
                <InputNumber
                  min={0}
                  max={10}
                  style={{ width: '100%' }}
                  placeholder={intl.formatMessage({ id: "RoomSettings.Please enter the number of suites" })}
                />
              </Form.Item>
            )}
          </div>
        </Col>
      </Row>

      {/* 操作按钮行 */}
      <Row justify="end" gutter={16}>
        <Col>
          <Button onClick={generate} type="primary">
            {intl.formatMessage({ id: "RoomSettings.Generate rooms" })}
          </Button>
        </Col>
        &emsp;
        <Col>
          <Button onClick={bePut}>
            {intl.formatMessage({ id: "RoomSettings.Storage" })}
          </Button>
        </Col>
          &emsp;
        <Col>
          <Button type="primary" danger onClick={() => setIsModalOpen(false)}>
            {intl.formatMessage({ id: "RoomSettings.Back" })}
          </Button>
        </Col>
      </Row>
    </Form>
      </Card>
      <br />

      {/* 表格数据 */}
      <ProTable
        defaultSize={'large'}
        columns={columns}
        actionRef={actionRef}
        cardBordered={false}
        dataSource={list}
        onRow={(record) => ({
          onClick: () => handleRowClick(record),
        })}
        editable={{
          type: 'multiple',
          actionRender: (row, config, dom) => [dom.save, dom.cancel],
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          onSave: async (rowKey, data, row) => {
            return;
          },
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          onValuesChange: (record, recordList) => {
            editRow(record);
          },
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        pagination={false}
        search={false}
        options={false}
        dateFormatter="string"
      />
    </>
  );
};

export default GenerateRooms;
